package com.ip;

import com.alibaba.fastjson.JSON;
import com.common.ResultBean;
import com.properties.WebProperties;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 白名单进行ip拦截
 */
public class IPHandlerInterceptor implements HandlerInterceptor {

    private WebProperties webProperties;

    public IPHandlerInterceptor(WebProperties webProperties) {
        this.webProperties = webProperties;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String realIP = IPUtils.getRealIP(request);
        // 如果在白名单中，则放行交由后续拦截器、应用程序处理
        // 否则直接拦截，返回错误信息
        if (webProperties.getIpWhitelist().contains(realIP)) {
            return true;
        }
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(JSON.toJSONString(ResultBean.error("该ip禁止访问目标接口")));
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
